package tools;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseEvent;
import application.CanvasView;
import tools.shapes.TwoEndShape;

public class TwoEndShapeTool extends Tool
{
	// Components
	protected CanvasView canvas;
	protected Point startingMousePosition;
	protected Point currentMousePosition;
	protected Color saveColor;
	protected TwoEndShape shape;
	
	// Constructor
	public TwoEndShapeTool(CanvasView c, TwoEndShape t)
	{
		if(c != null && t != null)
		{
			canvas = c;
			shape = t;
		}
		else
			throw new IllegalArgumentException();
	}
	
	/****Event Handler Methods***********************************************/
	/*  
	 * Establish starting point for next drawing
	 * 
	 * @see tools.Tool#mousePressed(java.awt.event.MouseEvent)
	 */
	public void mousePressed(MouseEvent e)
	{  
		startingMousePosition = e.getPoint();
		currentMousePosition = startingMousePosition;
		Graphics iBGraphics = canvas.getimageBufferGraphics();
		saveColor = iBGraphics.getColor( );
		iBGraphics.setXORMode(Color.lightGray);
		iBGraphics.setColor(Color.white);
		shape.drawOutline(iBGraphics,
				startingMousePosition.x,
				startingMousePosition.y,
				startingMousePosition.x,
				startingMousePosition.y);
		canvas.repaint();
	}

	/*
	 * Resizes the TwoEndShape and updates the shape outline
	 * 
	 * @see tools.Tool#mouseDragged(java.awt.event.MouseEvent)
	 */
	public void mouseDragged(MouseEvent e)
	{
		Point newMousePosition = e.getPoint();
		Graphics iBGraphics = canvas.getimageBufferGraphics(); 
		
		/* erase previous temporary figure by redrawing it */
		shape.drawOutline(iBGraphics,
				startingMousePosition.x,
				startingMousePosition.y,
				currentMousePosition.x, 
				currentMousePosition.y);

		/* draw new temporary figure */
		shape.drawOutline(iBGraphics,
				startingMousePosition.x,
				startingMousePosition.y,
				newMousePosition.x,
				newMousePosition.y);

		/* update current mouse coordinates */
		currentMousePosition = newMousePosition;
		canvas.repaint();
	}


	/*  
	 * Draws the finalized TwoEndShape
	 * 
	 * @see tools.Tool#mouseReleased(java.awt.event.MouseEvent)
	 */
	public void mouseReleased(MouseEvent e)
	{ 
		Graphics iBGraphics = canvas.getimageBufferGraphics();

	    /* Erase final temporary figure  */
	    shape.drawOutline(iBGraphics,
	    		startingMousePosition.x, 
	    		startingMousePosition.y,
	    		currentMousePosition.x, 
	    		currentMousePosition.y);
	    
	    /* Return graphics context to normal drawing mode and color */
	    iBGraphics.setPaintMode();
	    iBGraphics.setColor(saveColor);

	    /* Draw final"permanent" figure */
	    shape.draw(iBGraphics,
	    		startingMousePosition.x, 
	    		startingMousePosition.y,
	    		e.getPoint().x, 
	    		e.getPoint().y);
	    
		canvas.addGraphic(iBGraphics);
	    canvas.repaint();   
	}
}
